package action.back;

import hibernate.Page;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.Zone;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import service.ICommonService;
import utils.JsonUtils;
import utils.StringHelper;
import utils.WebUtils;
import action.vo.LoginInfo;
import config.Constant;


public class BaseAction {
	
	public boolean auth(){
		return request.getSession().getAttribute(Constant.LOGININFO)!=null;
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	public static final String APP_LOGIN = "app.login";
	public static final String APP_INDEX = "app.index";
	
	public static final String INDEX = "index";
	public static final String EDIT = "edit";
	public static final String LIST = "list";

	
	protected HttpServletResponse response = ServletActionContext.getResponse();
	protected HttpServletRequest request = ServletActionContext.getRequest();
	protected HttpSession session = ServletActionContext.getRequest().getSession();
	
	protected Page page;
	protected Integer start = 0;
	protected Integer limit = Constant.PAGE_SIZE;

	
	@Autowired
	protected ICommonService commonService;
	

	protected HttpServletResponse getResponse() {
		return response;
	}

	protected HttpServletRequest getRequest() {
		return request;
	}
	
	public LoginInfo getLoginInfo(HttpServletRequest request) {
		LoginInfo loginInfo = (LoginInfo)request.getSession().getAttribute(Constant.LOGININFO);
		return loginInfo;
	}
	public LoginInfo getLoginInfo() {
		LoginInfo loginInfo = (LoginInfo)request.getSession().getAttribute(Constant.LOGININFO);
		return loginInfo;
	}
	
	public void initServerInfo(){
		request.setAttribute("contextPath", request.getContextPath());
		request.setAttribute("serverPath", getServetPath(request));
		request.setAttribute("serverPort", String.valueOf(request.getServerPort()));
		request.setAttribute("serverName", request.getServerName());
	}
	
	protected void redirect(String path) {
		try {
			getResponse().sendRedirect(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	protected void forward(String path) {
		try {
			getRequest().getRequestDispatcher(path).forward(getRequest(), getResponse());
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String getContextPath(HttpServletRequest httpServletRequest) {
		String i = httpServletRequest.getContextPath();
		return i.endsWith("/") ? i : i + "/";
	}

	public String getServetPath(HttpServletRequest httpServletRequest) {
		String serverPath = httpServletRequest.getScheme() + "://"
				+ httpServletRequest.getServerName() + ":"
				+ httpServletRequest.getServerPort()
				+ httpServletRequest.getContextPath();

		return serverPath;
	}
	protected String render(String text, String contentType) {
		try {
			WebUtils.setNoCacheHeader(ServletActionContext.getResponse());
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType(contentType);
			response.getWriter().write(text);
		} catch (IOException e) {

		}

		return null;
	}

	/**
	 * 直接输出字符串.
	 */
	protected String renderText(String text) {
		return render(text, "text/plain;charset=UTF-8");
	}

	/**
	 * 直接输出HTML.
	 */
	protected String renderHtml(String html) {
		return render(html, "text/html;charset=UTF-8");
	}

	/**
	 * 直接输出XML.
	 */
	protected String renderXML(String xml) {
		return render(xml, "text/xml;charset=UTF-8");
	}

	protected String renderJson(String json) {
		return render(json, "text/json;charset=UTF-8");
	}
	

	protected String renderJs(String jsText) {
		return render(jsText, "application/x-javascript;charset=utf-8");
	}
	

	public Integer getLimit() {
		return limit!=null&&limit>0 ? limit : Constant.PAGE_SIZE;
	}

	public void setLimit(Integer limit) {
		this.limit = limit;
	}

	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}

	public Integer getStart() {
		return start;
	}

	public void setStart(Integer start) {
		this.start = start;
	}
	
	public ICommonService getCommonService() {
		return commonService;
	}

	public void setCommonService(ICommonService commonService) {
		this.commonService = commonService;
	}
	
	public DetachedCriteria zoneRestrion(DetachedCriteria detachedCriteria, String propName,String assignAddress) {
		
		if(assignAddress!=null && !"".equals(assignAddress)){
			while(assignAddress.length() > 0 && assignAddress.endsWith("0")){
				assignAddress = assignAddress.substring(0, assignAddress.length() - 1);
			}
			detachedCriteria.add(Restrictions.ilike(propName, ""+assignAddress+"%"));
		}
		else{
			LoginInfo LoginInfo = getLoginInfo();
			Zone zone = LoginInfo.getZone();
			if(zone!=null){
				String zoneCode = zone.getCode();
				while(zoneCode.length() > 0 && zoneCode.endsWith("0")){
					zoneCode = zoneCode.substring(0, zoneCode.length() - 1);
				}
				detachedCriteria.add(Restrictions.ilike(propName, ""+zoneCode+"%"));
			}
		}
		
		
		return detachedCriteria;
	}

	public DetachedCriteria zoneRestrion(DetachedCriteria dc, String propName) {
		return zoneRestrion(dc,propName,null);
	}

	protected void renderJson(Page page){
		Map<String, Object> jsonMap = new HashMap<String, Object>();
	    jsonMap.put("items",page.getItems());
	    jsonMap.put("total", page.getTotal());
	    renderJson(jsonMap);
	}
	
	protected void renderJson(Page page,Map<String, Object> jsonMap){
	    jsonMap.put("items",page.getItems());
	    jsonMap.put("total", page.getTotal());
	    renderJson(jsonMap);
	}
	
	protected void renderJson(Map<String, Object> jsonMap){
		 JSONObject jsonObject = JSONObject.fromObject(jsonMap,JsonUtils.configJson("yyyy-MM-dd"));
		 renderJson(jsonObject.toString());
	}
	protected void renderJson(Map<String, Object> jsonMap,JsonConfig config){
		 JSONObject jsonObject = JSONObject.fromObject(jsonMap,config);
		 renderJson(jsonObject.toString());
	}
	protected void renderJson(List list){
		JSONArray JSONArray = net.sf.json.JSONArray.fromObject(list, JsonUtils.configJson("yyyy-MM-dd"));
		renderJson(JSONArray.toString());
	}
	
	protected String getParameter(String paramName){
		return getParameter(paramName,false);
	}
	protected String getParameter(String paramName,String defaultValue){
		String tempStr =  getParameter(paramName,false);
		if(StringUtils.isEmpty(tempStr))
			tempStr = defaultValue;
		return tempStr;
	}
	
	protected String getParameter(String paramName,boolean setAttribute){
		String paramValue = request.getParameter(paramName);
		request.setAttribute(paramName, paramValue);
		return paramValue;
	}
	
	protected String getParameter(String paramName,boolean setAttribute,String defaultValue){
		String paramValue = request.getParameter(paramName);
		if(StringUtils.isEmpty(paramValue))
			paramValue = defaultValue;
		request.setAttribute(paramName, paramValue);
		return paramValue;
	}
	
	protected void setParameterAttributes(String... paramNameString){
		
		for(String i : paramNameString){
			setParameterAttribute(i,null);
		}
		
	}
	
	protected void setParameterAttribute(String paramNameString){
		setParameterAttribute(paramNameString,null);
	}
	protected void setParameterAttribute(String paramNameString, String defaultValue){
		getParameter(paramNameString, true,defaultValue);
	}
	
	public String truncate(String str,int bytelength,String sufix){
		return StringHelper.truncate(str, bytelength, sufix);
	}
}
